<template>
    <div class="search-suggestion">
        <van-cell v-for="(text,i) in suggestions" :key="i" @click="$emit('searchSuggestionEmit',text)">
            <template #icon>
                <van-icon name="search" />
            </template>
            <template #title>
                <div>
                    <span v-html="higthLight(text)"></span>
                </div>
            </template>
            
        </van-cell>
    </div>
</template>

<script>
import { getSearchKeysSuggestions } from '@/apis/search'
import { debounce } from 'lodash'
export default {
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            suggestions:[],
            timer:null
        }
    },
    watch: {
        searchText: {
            // handler(val) {
                // this.loadSearchKeysSuggestions(val)
                // clearTimeout(timer)
                // this.fangdou(val)
            // },
            // immediate:true
        // }
        handler: debounce(function(val) {
                    this.loadSearchKeysSuggestions(val)  
                },1000),
                immediate:true
        }
    },
    methods: {
        async loadSearchKeysSuggestions(val) {
            try {
                const {data: res} = await getSearchKeysSuggestions(val)
                this.suggestions = res.data.options | []
            } catch (error) {
                console.log(error);
            }
        },
        higthLight(text) {
            if (text) {
                var hightlightStr = `<span class="hightlight">${this.searchText}</span>`
                const reg = new RegExp(this.searchText,'gi');
                text.replace(reg,hightlightStr)
            }
            
            return text
        }
    }
}
</script>

<style lang="less" scoped>
.search-suggestion {
    :deep(span.hightlight) {
        color: #3296fa;
    }
}
</style>